import json
import os
from fastapi import APIRouter, HTTPException, Query, Body
from typing import List, Dict, Any

from config import FileHandle
from config.FileHandle import MCP_INSTALL_TOOLS_PATH
from mcpTool.mcpDirectoryHandle import get_all_projects, search_repositories, add_project, add_projects, get_project_by_id, refresh_agent_data, delete_project

router = APIRouter(prefix="/api/mcpTool", tags=["mcpTool"])

@router.get("/projects", response_model=List[Dict[str, Any]])
async def get_mcp_projects():
    """获取所有MCP项目，包括本地配置"""
    try:
        return get_all_projects()
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/search", response_model= List[Dict[str, Any]])
async def search_mcp_repos(q: str = Query(..., description="搜索关键词"),
                           token: str = Query(None, description="GitHub Token")):
    """调用GitHub API搜索仓库，返回 URL 列表"""
    try:
        return search_repositories(q, token)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/project", response_model=Dict[str, Any])
async def add_mcp_project(project: Dict[str, Any] = Body(...)):
    """添加新项目"""
    try:
        return add_project(project)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/projects/batch", response_model=List[Dict[str, Any]])
async def add_mcp_projects(projectsData: List[Dict[str, Any]]):
    """批量添加项目"""
    try:
        return add_projects(projectsData)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/project/{project_id}", response_model=Dict[str, Any])
async def get_mcp_project(project_id: str):
    """按ID获取项目"""
    try:
        project = get_project_by_id(project_id)
        if not project:
            raise HTTPException(status_code=404, detail="项目不存在")
        return project
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/refresh", response_model=List[Dict[str, Any]])
async def refresh_mcp_data():
    """刷新代理数据"""
    try:
        return refresh_agent_data()
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/project/{project_id}", response_model=List[Dict[str, Any]])
async def delete_mcp_project(project_id: str):
    """删除指定ID的项目并返回更新后的列表"""
    try:
        return delete_project(project_id)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/save-tool-config")
async def save_tool_config(data: Dict[str, Any] = Body(...)):
    """保存MCP工具配置到JSON文件

    Args:
        data: 包含配置的字典，格式为 {"config": {...}}

    Returns:
        保存状态
    """
    try:
        input_config = data.get("config")
        if not input_config:
            raise HTTPException(status_code=400, detail="缺少配置数据")
        
        # 转换输入格式
        config = {}
        if "mcpServers" in input_config:
            # 获取第一个服务键
            server_keys = list(input_config["mcpServers"].keys())
            if not server_keys:
                raise HTTPException(status_code=400, detail="mcpServers对象为空")
            
            server_key = server_keys[0]
            server_config = input_config["mcpServers"][server_key]
            
            # 构建标准格式
            config = {
                "id": f"mcp-{len(server_key)}",  # 根据名称生成ID，可自定义规则
                "name": f"mcp-server-{server_key}",  # 服务名称
                "description": f"使用{server_key}服务",  # 描述
                "command": server_config.get("command", ""),
                "args": server_config.get("args", [])
            }
        else:
            # 已经是标准格式
            config = input_config
        
        # 验证必要字段
        required_fields = ["id", "name", "command"]
        missing_fields = [field for field in required_fields if field not in config]
        if missing_fields:
            raise HTTPException(
                status_code=400, 
                detail=f"配置缺少必要字段: {', '.join(missing_fields)}"
            )
        
        # 读取现有配置
        existing_configs = []
        if os.path.exists(MCP_INSTALL_TOOLS_PATH):
            try:
                with open(MCP_INSTALL_TOOLS_PATH, "r", encoding="utf-8") as f:
                    existing_configs = json.load(f)
                    if not isinstance(existing_configs, list):
                        existing_configs = []
            except json.JSONDecodeError:
                # 文件存在但格式无效，重置为空列表
                existing_configs = []
        
        # 检查是否需要更新现有配置
        updated = False
        for i, item in enumerate(existing_configs):
            if item.get("id") == config.get("id"):
                existing_configs[i] = config
                updated = True
                break
        
        # 如果没有更新现有配置，则添加新配置
        if not updated:
            existing_configs.append(config)
        
        # 保存配置
        with open(MCP_INSTALL_TOOLS_PATH, "w", encoding="utf-8") as f:
            json.dump(existing_configs, f, ensure_ascii=False, indent=2)
        
        return {
            "status": "success", 
            "message": "MCP工具配置已保存",
            "id": config.get("id")
        }
    
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"保存配置失败: {str(e)}")

@router.get("/tool-configs", response_model=List[Dict[str, Any]])
async def get_tool_configs():
    """获取所有已保存的MCP工具配置

    Returns:
        工具配置列表
    """
    try:
        if not os.path.exists(MCP_INSTALL_TOOLS_PATH):
            return []
        
        with open(MCP_INSTALL_TOOLS_PATH, "r", encoding="utf-8") as f:
            configs = json.load(f)
            if not isinstance(configs, list):
                return []
            return configs
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取配置失败: {str(e)}")

@router.get("/tool-config/{tool_id}")
async def get_tool_config(tool_id: str):
    """根据ID获取特定的MCP工具配置

    Args:
        tool_id: 工具ID

    Returns:
        工具配置
    """
    try:
        if not os.path.exists(MCP_INSTALL_TOOLS_PATH):
            raise HTTPException(status_code=404, detail="配置文件不存在")
        
        with open(MCP_INSTALL_TOOLS_PATH, "r", encoding="utf-8") as f:
            configs = json.load(f)
            
        if not isinstance(configs, list):
            raise HTTPException(status_code=404, detail="配置格式无效")
            
        for config in configs:
            if config.get("id") == tool_id:
                return config
                
        raise HTTPException(status_code=404, detail=f"未找到ID为 {tool_id} 的配置")
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取配置失败: {str(e)}")